package com.liqi.web.controller.device;

import com.liqi.common.annotation.Log;
import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.AjaxResult;
import com.liqi.common.core.page.TableDataInfo;
import com.liqi.common.enums.BusinessType;
import com.liqi.common.utils.DateUtils;
import com.liqi.common.utils.poi.ExcelUtil;
import com.liqi.device.domain.DvGroup;
import com.liqi.device.mapper.DvGroupMapper;
import com.liqi.device.service.IDvGroupService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 分组Controller
 *
 * @author Lwy
 * @date 2022-03-28
 */
@Api(tags = "分组Controller")
@RestController
@RequestMapping("/device/group")
public class DvGroupController extends BaseController
{
    @Autowired
    private IDvGroupService dvGroupService;

    @Autowired
    private DvGroupMapper dvGroupMapper;
    /**
     * 查询分组列表
     */
    @ApiOperation("查询分组列表")
    @PreAuthorize("@ss.hasPermi('device:group:list')")
    @GetMapping("/list")
    public TableDataInfo list(DvGroup dvGroup)
    {
        if(dvGroup.getName()!=null){
            dvGroup.setParentId(null);
        }
        startPage();
        List<DvGroup> list = dvGroupService.selectDvGroupList(dvGroup);
        return getDataTable(list);
    }

    /**
     * 查询分组列表 给设备投放使用
     */
    @ApiOperation("查询分组列表 给设备投放使用")
    /*@PreAuthorize("@ss.hasPermi('device:group:listForDevice')")*/
    @GetMapping("/listForDevice")
    public TableDataInfo listForDevice(DvGroup dvGroup)
    {
        startPage();
        List<DvGroup> list = dvGroupService.selectDvGroupListForDevice(dvGroup);
        return getDataTable(list);
    }

    /**
     * 导出分组列表
     */
    @ApiOperation("导出分组列表")
    @PreAuthorize("@ss.hasPermi('device:group:export')")
    @Log(title = "分组", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DvGroup dvGroup)
    {
        dvGroup.setParentId(null);
        List<DvGroup> list = dvGroupService.selectDvGroupList(dvGroup);
        ExcelUtil<DvGroup> util = new ExcelUtil<DvGroup>(DvGroup.class);
        util.exportExcel(response, list, "分组数据");
    }

    /**
     * 获取分组详细信息
     */
    @ApiOperation("获取分组详细信息")
    @PreAuthorize("@ss.hasPermi('device:group:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(dvGroupService.selectDvGroupById(id));
    }

    /**
     * 新增分组
     */
    @ApiOperation("新增分组")
    @PreAuthorize("@ss.hasPermi('device:group:add')")
    @Log(title = "分组", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DvGroup dvGroup)
    {
        try{
        if(dvGroup.getName().trim()==""){
        }
        Long id = dvGroup.getParentId();
        dvGroup.setCreateBy(getUsername());
        dvGroup.setCreateTime(DateUtils.getNowDate());
        dvGroup.setUpdateBy(getUsername());
        dvGroup.setUpdateTime(DateUtils.getNowDate());
        if(getDeptId()!=null) {
            dvGroup.setDeptId(getDeptId().toString());
        }else {
            dvGroup.setDeptId("");
        }
        dvGroup.setCreateUserId(getUserId().toString());
        dvGroup.setHaveChildren("0");

        if(id!=0) {
         DvGroup dvGroup1 = dvGroupService.selectDvGroupById(id);
         dvGroup1.setHaveChildren("1");
         dvGroupService.updateDvGroup(dvGroup1);
         dvGroup.setAncestors(dvGroup1.getAncestors()+","+id);
        }
        else {
                dvGroup.setAncestors("0");
            }
            dvGroupService.insertDvGroup(dvGroup);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("该分组已有，请勿重复添加");
        }

        return AjaxResult.success("新增成功");
    }

    /**
     * 修改分组
     */
    @ApiOperation("修改分组")
    @PreAuthorize("@ss.hasPermi('device:group:edit')")
    @Log(title = "分组", businessType = BusinessType.UPDATE)
    @PutMapping
        public AjaxResult edit(@RequestBody DvGroup dvGroup)
    {
        // 修改为已有的分组名称判断
        //todo 修改分组名称
        Integer count = dvGroupMapper.getByName(dvGroup.getName(),dvGroup.getId());
        if (count > 0 && dvGroup.getParentId().equals(dvGroup.getOldParentId())) {
            return AjaxResult.error(" 已经存在该分组名称");
        }
        Long id = dvGroup.getId();
        Long parentId = dvGroup.getParentId();
        Long oldParentId = dvGroup.getOldParentId();
        DvGroup dvGroupOld = dvGroupService.selectDvGroupById(oldParentId);
        DvGroup dvGroup1 = dvGroupService.selectDvGroupById(parentId);
        List<DvGroup> dvGroups = dvGroupService.selectDvGroupByParentId(id);

        dvGroup.setUpdateBy(getUsername());
        dvGroup.setUpdateTime(DateUtils.getNowDate());

        if(dvGroups.size()==0){
            dvGroup.setHaveChildren("0");
        }else {
            dvGroup.setHaveChildren("1");


        }
        if(parentId!=0){

            dvGroup1.setHaveChildren("1");
            dvGroupService.updateDvGroup(dvGroup1);
            dvGroup.setAncestors(dvGroup1.getAncestors()+","+parentId);
        }else {
            dvGroup.setAncestors("0");
        }


        dvGroupService.updateDvGroup(dvGroup);
        if(oldParentId!=0){
            if(dvGroupService.selectDvGroupByParentId(oldParentId).size()!=0){
                dvGroupOld.setHaveChildren("1");
            }else {
                dvGroupOld.setHaveChildren("0");
            }
            dvGroupService.updateDvGroup(dvGroupOld);
        }

        checkHaveChildren(id);

        return toAjax(dvGroupService.updateDvGroup(dvGroup));   
    }

    /**
     * 删除分组
     */
    @ApiOperation("删除分组")
    @PreAuthorize("@ss.hasPermi('device:group:remove')")
    @Log(title = "分组", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for(int i=0;i<ids.length;i++) {
            DvGroup dvGroup = dvGroupService.selectDvGroupById(ids[i]);

            if (dvGroup == null) {
                if (i != ids.length - 1) {
                    continue;
                } else {
                    return AjaxResult.success("删除成功");
                }
            } else {
                dvGroupService.deleteDvGroupByAncestors(ids[i]);
                dvGroupService.deleteDvGroupById(ids[i]);
                if (dvGroup.getParentId()!=0){
                    DvGroup dvGroupParent = dvGroupService.selectDvGroupById(dvGroup.getParentId());
                List<DvGroup> dvGroups = dvGroupService.selectDvGroupByParentId(dvGroup.getParentId());

                if (dvGroups.size() != 0) {
                    dvGroupParent.setHaveChildren("1");
                } else {
                    dvGroupParent.setHaveChildren("0");
                }
                dvGroupService.updateDvGroup(dvGroupParent);
            }

        }



        }
        return AjaxResult.success("删除成功");
    }
    /**
     * 给前端调用：查询下一级的数据
     *
     * @param id 上级id
     * @return 分组集合
     */
    @ApiOperation("查询下一级的数据")
    @GetMapping(value = "/getGroup")
    public TableDataInfo getGroup(@RequestParam(value="id", required=true)Long id)
    {

        startPage();
        List<DvGroup> list = dvGroupService.selectDvGroupByParentId(id);
        return getDataTable(list);
    }

    public List<DvGroup> checkHaveChildren(Long id) {
        List<DvGroup> dvGroups = dvGroupService.selectDvGroupByParentId(id);
        DvGroup dvGroupOld = dvGroupService.selectDvGroupById(id);
        ArrayList<Long> ids =new ArrayList<>();


        for (int i=0;i<dvGroups.size(); i++) {

            dvGroups.get(i).setAncestors(dvGroupOld.getAncestors() + "," + dvGroups.get(i).getParentId());
            dvGroupService.updateDvGroup(dvGroups.get(i));
            if (dvGroups.get(i).getHaveChildren().equals("1")) {
               ids.add(dvGroups.get(i).getId());
            }

        }
        if(ids.size()!=0) {
            for (int j = 0; j < ids.size(); j++) {
                id = ids.get(j);
                checkHaveChildren(id);
            }
        }
        return dvGroups;
    }
}
